package com.moss.system.service.impl;

import com.moss.common.entity.SysPostEntity;
import com.moss.common.entity.SysRoleEntity;
import com.moss.common.exception.ServiceException;
import com.moss.system.mapper.PostMapper;
import com.moss.system.service.PostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PostServiceImpl implements PostService {


    @Resource
    PostMapper postMapper;


    @Override
    public List<SysPostEntity> selectList(SysPostEntity post) {
        return postMapper.selectList(post);
    }

    @Override
    public void savePost(SysPostEntity post) {
        checkParam(post,true);
        postMapper.insert(post);
    }

    private void checkParam(SysPostEntity post, boolean save) {
        String postName = post.getPostName();
        if (StringUtils.isEmpty(postName)){
            throw new ServiceException("新增失败-岗位名为空");
        }
        SysPostEntity postByName = postMapper.selectPostByName(postName);
        if (save && postByName != null){
            throw new ServiceException("新增失败-岗位名已存在");
        }
        if (!save && postByName != null && !post.getPostId().equals(postByName.getPostId())){
            throw new ServiceException("修改失败-岗位名已存在");
        }
        String postCode = post.getPostCode();
        if (StringUtils.isEmpty(postCode)){
            throw new ServiceException("新增失败-岗位编码为空");
        }
        SysPostEntity postByCode = postMapper.selectPostByCode(postCode);
        if (save && postByCode != null){
            throw new ServiceException("新增失败-岗位编码已存在");
        }
        if (!save && postByCode != null && !post.getPostId().equals(postByCode.getPostId())){
            throw new ServiceException("修改失败-岗位编码已存在");
        }
    }


    @Override
    public SysPostEntity selectById(Long postId) {
        return postMapper.selectById(postId);
    }

    @Override
    public void updatePost(SysPostEntity post) {
        checkParam(post,false);
        postMapper.updateById(post);
    }

    @Override
    public void deletePost(Long[] postIds) {
        for (Long postId : postIds) {
            SysPostEntity sysPost = selectById(postId);
            if (postMapper.countUserByPost(postId) > 0){
                throw new ServiceException(String.format("%1$s已分配,不能删除", sysPost.getPostName()));
            }
        }
        postMapper.deleteBatchIds(postIds);
    }


    @Override
    public List<SysPostEntity> selectPostAll() {
        return selectList(new SysPostEntity());
    }

    @Override
    public List<Long> selectPostIdListByUserId(String userId) {
        return postMapper.selectPostIdListByUserId(userId);
    }
}
